package com.atguigu.flink.day03;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Felix
 * @date 2024/8/12
 * 该案例演示了聚合算子-reduce
 * 需求：计算每个传感器采集的水位和
 *      如果流中只有一条数据，reduce方法不会被执行
 *      reduce(value1,value2)
 *          value1:累加的结果
 *          value2:流中新来的数据
 */
public class Flink14_Transform_Reduce {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //TODO 2.从指定的网络端口中读取数据
        DataStreamSource<String> ds = env.socketTextStream("hadoop102", 8888);
        //将流中数据进行类型转换 string->WaterSensor
        SingleOutputStreamOperator<WaterSensor> wsDS = ds.map(
                new WaterSensorMapFunction()
        );

        //TODO 3.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyedDS = wsDS.keyBy(WaterSensor::getId);
        //KeyedStream<WaterSensor, String> keyedDS = wsDS.keyBy(WaterSensor::getId);
        //TODO 4.求和
        SingleOutputStreamOperator<WaterSensor> reduceDS = keyedDS.reduce(
                new ReduceFunction<WaterSensor>() {
                    @Override
                    public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                        System.out.println("value1 : " + value1);
                        System.out.println("value2 : " + value2);
                        value1.setVc(value1.vc + value2.vc);
                        return value1;
                    }
                }
        );
        //TODO 5.打印
        reduceDS.print("~~~");
        //TODO 6.提交作业
        env.execute();
    }
}
